from urllib import urlretrieve as uretr
import urllib
import os
import os.path
import sys
import re
import shutil
import glob

lastlen=0
def download_callback(blocks, blocksize, total):
	global lastlen
	prc=blocks*blocksize*100/total
	if prc>100:
		prc=100
	backsp=''.join(['\b']*lastlen)
	print backsp,
	text=''.join([str(blocks*blocksize),'/',str(total),'  ',str(prc)+'%'])

	if total == -1:
		text=str(blocks*blocksize)+' bytes so far, total size unavailable'
	lastlen=len(text)+2
	print text,

def download(url, out, silent=False):
	global lastlen
	print 'Downloading file',os.path.basename(url)
	if silent:
		uretr(url,out)
	else:
		lastlen=0
		print '---> ',
		uretr(url,out,download_callback)
		print ''
def multidownload(urls, outs, silent=False):
	global lastlen
	print 'Downloading',len(urls),'files'
	if silent:
		for i in xrange(0,len(urls)):
			uretr(urls[i], outs[i])
	else:
		for i in xrange(0,len(urls)):
			lastlen=0
			print str(i+1)+'/'+str(len(urls)),os.path.basename(urls[i]),'---> ',
			uretr(urls[i],outs[i],download_callback)
			print ''

def install_pygtk():
	urls = [
		'http://ftp.gnome.org/pub/GNOME/binaries/win32/pycairo/1.4/pycairo-1.4.12-1.win32-py2.5.exe',
		'http://ftp.gnome.org/pub/GNOME/binaries/win32/pygobject/2.14/pygobject-2.14.1-1.win32-py2.5.exe',
		'http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.12/pygtk-2.12.1-1.win32-py2.5.exe',
		]
	outs = map(os.path.basename, urls)
	multidownload(urls, outs)
	for cmd in outs:
		os.system(cmd)
	pass
	
def install_easy():
	download('http://peak.telecommunity.com/dist/ez_setup.py','ez_setup.py')
	os.system(os.path.join(sys.exec_prefix,'python')+' ez_setup.py')
	pass

def install_pycha(eicmd):
	os.system(eicmd+' pycha')

def install_gtk():
	url='http://mesh.dl.sourceforge.net/sourceforge/gtk-win/gtk2-runtime-2.12.6-2008-02-02-ash.exe' 
#	url='http://surfnet.dl.sourceforge.net/sourceforge/gladewin32/gtk-2.10.6-win32-1.exe'
	download(url,os.path.basename(url))
	os.system(os.path.basename(url))
	print 'Now restart your computer for changes made by GTK+ installer to take part'
	os.system('pause')
	sys.exit()

def install_gtkthemes():
	url='http://garr.dl.sourceforge.net/sourceforge/gtk-win/gtk2-themes-2008-01-21-ash.exe'
	download(url,os.path.basename(url))
	os.system(os.path.basename(url))

def install_pysqlite(eicmd):
	os.system(eicmd+' pysqlite')

print '*** CUBE ASSISTANT DOWNLOAD SCRIPT ***\n'


print ' + INSTALLING GTK+'
gtkpth=''
try:
	path = os.environ['PATH'].split(';')
	regexp = re.compile('%(.+)%')
	for pth in xrange(0,len(path)):
                matches = regexp.finditer(path[pth])
                if matches == None: continue
                for match in matches:
                        path[pth]=path[pth].replace('%'+match.groups()[0]+'%',os.path.expandvars('$'+match.groups()[0]))
                    
	for pth in path:
		if len(glob.glob(os.path.join(pth,'libgtk-win32-2*')))>0:
			gtkpth=pth

	if gtkpth == '':
		raise False
	print 'GTK+ already installed, proceeding\n'
except:
	install_gtk()

print ' + INSTALLING GTK+ THEMES'
try:
	if not os.path.exists(os.path.join(gtkpth,'..','share','themes','Rezlooks-graphite')):
		raise False

	print 'GTK+ themes already installed, proceeding\n'
except:
	install_gtkthemes()
	
print ' + INSTALLING PYGTK'
try:
	import pygtk
	pygtk.require('2.0')
	import cairo
	import gobject
	import gtk

	print 'PyGTK already installed, proceeding\n'
except:
	install_pygtk()

print ' + INSTALLING EASY_INSTALL'

eicmd='easy_install'

if os.name=='nt':
	eicmd=os.path.join(sys.exec_prefix,'Scripts','easy_install')
if os.system(eicmd+' -h > NUL 2> NUL') != 0:
	install_easy()
else:
	print 'easy_install already installed, proceeding\n'

print ' + INSTALLING PYSQLITE'
try:
	import pysqlite2
	
	print 'PySqlite already installed, proceeding\n'
except:
	install_pysqlite(eicmd)

print ' + INSTALLING PYCHA'
try:
	import pycha

	print 'PyCha already installed, proceeding\n'
except:
	install_pycha(eicmd)

print ' + DOWNLOADING CUBE ASSISTANT'

def compose_filelist(url):
	ret=[]
	txt = urllib.urlopen(url).read()

	regexp = re.compile('<a href="([a-zA-z0-9\-\./_]+)">([a-zA-Z0-9\-\./_]+)</a>')

	for match in regexp.finditer(txt):
		if match.groups()[1] == '..':
			continue

		if match.groups()[0][-1] == '/':
			ret.extend(compose_filelist(os.path.join(url,match.groups()[0])))
		else:
			ret.append(os.path.join(url,match.groups()[0]))
	
	return ret

print 'Walking through SVN tree'
svnpath='http://cubeassistant.googlecode.com/svn/trunk/'
urls = compose_filelist(svnpath)
outs = map(lambda x:os.path.join('cubeassistant',x[len(svnpath):]),urls)
print 'Creating dir hierarchy'

cubeasspth=''

for pth in outs:
	if pth.find('modTimer/dist/')!=-1:
		cubeasspth=pth
	dir = os.path.dirname(pth)
	if not os.path.exists(dir):
		os.makedirs(dir)

multidownload(urls, outs)

print ' + INSTALLING CUBEASS'
try:
	import cubeass

	print 'Cubeass already installed, proceeding\n'
except:
	os.system(cubeasspth.replace('/','\\'))

print ' + INSTALLING GLADE DLLS'

shutil.copy(os.path.join('cubeassistant','misc','gladedlls.exe'),'.')
os.system('gladedlls.exe')

print '*** CUBE ASSISTANT HAVE BEEN INSTALLED ***\n'

os.system('pause')
